package cn.edu.zut.soft.student.controller;

import cn.edu.zut.soft.student.bean.ResultBean;
import cn.edu.zut.soft.student.service.login.LoginBo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author ChrisPhantom
 * @CreatDate 2021/02/14 18:50
 */

@Controller
public class LoginController {
    @Autowired
    private LoginBo loginBo;

    @RequestMapping("/")
    public String index(HttpSession session, HttpServletResponse response) throws Exception {
        if (session.getAttribute("LoginUser") != null) {
            String classify = (String) session.getAttribute("classify");
            response.sendRedirect("/" + classify);
        }
        return "pages/login";
    }

    @ResponseBody
    @RequestMapping("/login")
    public ResultBean<String> login(String username, String password) {
        String handleLogin = loginBo.handleLogin(username, password);
        ResultBean<String> resultBean = new ResultBean<>(handleLogin);
        if ("/login".equals(handleLogin)) {
            resultBean.setCode(ResultBean.NO_LOGIN);
        }
        return resultBean;
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:/";
    }
}
